<!DOCTYPE html>
<html>
<head>
    <title>Linux防护系统</title>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/pako@2.1.0/dist/pako.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .panel {
            border: 1px solid #ddd;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        button {
            padding: 5px 10px;
            margin: 5px;
            cursor: pointer;
        }
        .success { background: #4CAF50; color: white; }
        .danger { background: #f44336; color: white; }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .stat-card {
            background: #f5f5f5;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .stat-title {
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
        }
        
        .progress-bar {
            width: 100%;
            height: 10px;
            background: #ddd;
            border-radius: 5px;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background: #4CAF50;
            transition: width 0.3s ease;
        }
        
        .warning { background: #ff9800; }
        .critical { background: #f44336; }
        
        .log-container {
            margin-top: 10px;
        }
        
        .log-entries {
            max-height: 400px;
            overflow-y: auto;
            background: #f8f8f8;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
        }
        
        .log-entry {
            font-family: monospace;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        
        .log-entry.error { color: #f44336; }
        .log-entry.warning { color: #ff9800; }
        .log-entry.info { color: #2196F3; }
        
        .settings-form {
            display: grid;
            gap: 15px;
            max-width: 500px;
        }
        
        .form-group {
            display: grid;
            gap: 5px;
        }
        
        .form-group input[type="number"],
        .form-group input[type="email"] {
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        
        .charts-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin: 20px 0;
        }
        
        .chart-container {
            background: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        @media (max-width: 1200px) {
            .charts-grid {
                grid-template-columns: 1fr;
            }
        }

        .network-interface {
            background: #f5f5f5;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
        }
        
        .interface-info {
            margin-left: 20px;
        }
        
        .interface-info p {
            margin: 5px 0;
        }

        .process-tree {
            margin-top: 15px;
        }

        .process-filters {
            margin-bottom: 15px;
            display: flex;
            gap: 10px;
        }

        .process-filters input,
        .process-filters select {
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }

        .process-list {
            margin-top: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
        }

        .process-item {
            display: flex;
            align-items: center;
            padding: 10px 15px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .process-item:last-child {
            border-bottom: none;
        }

        .process-item:hover {
            background-color: #f5f5f5;
        }

        .process-item .info {
            flex: 1;
        }

        .process-item .stats {
            display: flex;
            gap: 20px;
            color: #666;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 15px;
            padding: 10px;
            background: #f5f5f5;
            border-radius: 5px;
        }

        .pagination button {
            padding: 5px 15px;
            border: none;
            background: #2196F3;
            color: white;
            border-radius: 3px;
            cursor: pointer;
        }

        .pagination button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .process-summary {
            display: flex;
            gap: 20px;
            padding: 10px;
            background: #f5f5f5;
            border-radius: 5px;
            margin-bottom: 15px;
        }

        .process-summary span {
            color: #666;
        }

        .process-summary strong {
            color: #333;
        }

        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 5px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }

        .close {
            float: right;
            cursor: pointer;
            font-size: 20px;
        }

        .modal-actions {
            margin-top: 15px;
            text-align: right;
        }

        /* 添加侧边栏样式 */
        .layout {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background: #2c3e50;
            color: white;
            padding: 20px 0;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
        }

        .main-content {
            flex: 1;
            margin-left: 250px;
            padding: 20px;
        }

        .menu-item {
            padding: 15px 25px;
            cursor: pointer;
            transition: background 0.3s;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .menu-item:hover {
            background: #34495e;
        }

        .menu-item.active {
            background: #3498db;
        }

        /* 内容区域样式 */
        .content-section {
            display: none;
        }

        .content-section.active {
            display: block;
        }

        /* 顶部导航栏 */
        .top-bar {
            background: white;
            padding: 15px 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .breadcrumb {
            font-size: 18px;
            color: #333;
        }

        /* 进程管理样式 */
        .process-controls {
            margin-bottom: 20px;
        }

        .process-tabs {
            display: flex;
            gap: 5px;
            margin-bottom: 15px;
        }

        .tab-button {
            padding: 8px 15px;
            border: none;
            background: #f5f5f5;
            cursor: pointer;
            border-radius: 3px;
        }

        .tab-button.active {
            background: #2196F3;
            color: white;
        }

        .tab-content {
            display: none;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 5px;
        }

        .tab-content.active {
            display: block;
        }

        .resource-chart {
            height: 200px;
            margin: 15px 0;
        }

        .file-list, .connection-list {
            max-height: 200px;
            overflow-y: auto;
        }

        .process-tree {
            padding-left: 20px;
        }

        .process-tree-item {
            margin: 5px 0;
            padding: 5px;
            border-left: 2px solid #ddd;
        }

        /* 添加进程列表错误样式 */
        .process-item.error {
            background-color: #ffebee;
            color: #c62828;
            padding: 15px;
            text-align: center;
        }

        .status {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .status.running { background: #4CAF50; }
        .status.sleeping { background: #FFC107; }
        .status.zombie { background: #F44336; }
        .status.unknown { background: #9E9E9E; }

        /* 添加下拉框样式 */
        select {
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: white;
            font-size: 14px;
            width: 100px;
        }
        
        select:focus {
            outline: none;
            border-color: #4CAF50;
        }
    </style>
</head>
<body>
    <div class="layout">
        <!-- 侧边菜单 -->
        <div class="sidebar">
            <h2 style="padding: 0 25px; margin-bottom: 20px;">Linux防护系统</h2>
            <div class="menu-item active" onclick="showSection('dashboard')">
                <i class="fas fa-tachometer-alt"></i>系统仪表盘
            </div>
            <div class="menu-item" onclick="showSection('firewall')">
                <i class="fas fa-shield-alt"></i>防火墙管理
            </div>
            <div class="menu-item" onclick="showSection('process')">
                <i class="fas fa-microchip"></i>进程管理
            </div>
            <div class="menu-item" onclick="showSection('network')">
                <i class="fas fa-network-wired"></i>网络监控
            </div>
            <div class="menu-item" onclick="showSection('logs')">
                <i class="fas fa-clipboard-list"></i>日志查看
            </div>
            <div class="menu-item" onclick="showSection('settings')">
                <i class="fas fa-cog"></i>系统设置
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="main-content">
            <div class="top-bar">
                <div class="breadcrumb">系统仪表盘</div>
                <div class="user-info">
                    最后更新: <span id="timestamp">{{ system_stats['timestamp'] if system_stats else '' }}</span>
                </div>
            </div>

            <!-- 仪表盘 -->
            <div id="dashboard" class="content-section active">
                <!-- 系统状态卡片 -->
                <div class="stats-grid">
                    <!-- CPU状态 -->
                    <div class="stat-card">
                        <div class="stat-title">CPU使用率</div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: {{ system_stats['cpu']['percent'] if system_stats and 'cpu' in system_stats else 0 }}%"></div>
                        </div>
                        <p>{{ system_stats['cpu']['percent'] if system_stats and 'cpu' in system_stats else 0 }}% 
                           ({{ system_stats['cpu']['cores'] if system_stats and 'cpu' in system_stats else 1 }}核心)</p>
                    </div>
                    
                    <!-- 内存状态 -->
                    <div class="stat-card">
                        <div class="stat-title">内存使用率</div>
                        <div class="progress-bar">
                            <div class="progress-fill {% if system_stats and 'memory' in system_stats %}{% if system_stats['memory']['percent'] > 80 %}critical{% elif system_stats['memory']['percent'] > 60 %}warning{% endif %}{% endif %}" 
                                 style="width: {{ system_stats['memory']['percent'] if system_stats and 'memory' in system_stats else 0 }}%"></div>
                        </div>
                        <p>{{ (system_stats['memory']['used'] / 1024 / 1024 / 1024) | round(2) if system_stats and 'memory' in system_stats else 0 }}GB / 
                           {{ (system_stats['memory']['total'] / 1024 / 1024 / 1024) | round(2) if system_stats and 'memory' in system_stats else 0 }}GB 
                           ({{ system_stats['memory']['percent'] if system_stats and 'memory' in system_stats else 0 }}%)</p>
                    </div>
                    
                    <!-- 磁盘状态 -->
                    <div class="stat-card">
                        <div class="stat-title">磁盘使用率</div>
                        <div class="progress-bar">
                            <div class="progress-fill {% if system_stats and 'disk' in system_stats %}{% if system_stats['disk']['percent'] > 90 %}critical{% elif system_stats['disk']['percent'] > 70 %}warning{% endif %}{% endif %}" 
                                 style="width: {{ system_stats['disk']['percent'] if system_stats and 'disk' in system_stats else 0 }}%"></div>
                        </div>
                        <p>{{ (system_stats['disk']['used'] / 1024 / 1024 / 1024) | round(2) if system_stats and 'disk' in system_stats else 0 }}GB / 
                           {{ (system_stats['disk']['total'] / 1024 / 1024 / 1024) | round(2) if system_stats and 'disk' in system_stats else 0 }}GB 
                           ({{ system_stats['disk']['percent'] if system_stats and 'disk' in system_stats else 0 }}%)</p>
                    </div>
                    
                    <!-- 网络状态 -->
                    <div class="stat-card">
                        <div class="stat-title">网络状态</div>
                        <p>
                            发送: {{ (system_stats['network']['bytes_sent'] / 1024 / 1024) | round(2) if system_stats and 'network' in system_stats else 0 }}MB<br>
                            接收: {{ (system_stats['network']['bytes_recv'] / 1024 / 1024) | round(2) if system_stats and 'network' in system_stats else 0 }}MB<br>
                            连接数: {{ system_stats['network']['connections']['ESTABLISHED'] if system_stats and 'network' in system_stats and 'connections' in system_stats['network'] else 0 }}
                        </p>
                    </div>
                    
                    <!-- CPU详细信息 -->
                    <div class="stat-card">
                        <div class="stat-title">CPU详细信息</div>
                        <p>频率: {{ system_stats['cpu']['frequency']['current'] if system_stats and 'cpu' in system_stats and 'frequency' in system_stats['cpu'] else 0 }}MHz</p>
                        <p>负载(1/5/15分钟):</p>
                        <p>{{ system_stats['cpu']['load_average']['1min'] if system_stats and 'cpu' in system_stats and 'load_average' in system_stats['cpu'] else 0 }} / 
                           {{ system_stats['cpu']['load_average']['5min'] if system_stats and 'cpu' in system_stats and 'load_average' in system_stats['cpu'] else 0 }} / 
                           {{ system_stats['cpu']['load_average']['15min'] if system_stats and 'cpu' in system_stats and 'load_average' in system_stats['cpu'] else 0 }}</p>
                    </div>
                    
                    <!-- 交换分区状态 -->
                    <div class="stat-card">
                        <div class="stat-title">交换分区</div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: {{ system_stats['memory']['swap']['percent'] if system_stats and 'memory' in system_stats and 'swap' in system_stats['memory'] else 0 }}%"></div>
                        </div>
                        <p>{{ (system_stats['memory']['swap']['used'] / 1024 / 1024 / 1024) | round(2) if system_stats and 'memory' in system_stats and 'swap' in system_stats['memory'] else 0 }}GB / 
                           {{ (system_stats['memory']['swap']['total'] / 1024 / 1024 / 1024) | round(2) if system_stats and 'memory' in system_stats and 'swap' in system_stats['memory'] else 0 }}GB</p>
                    </div>
                    
                    <!-- 磁盘IO -->
                    <div class="stat-card">
                        <div class="stat-title">磁盘IO</div>
                        <p>读取: {{ (system_stats['disk']['io']['read_bytes'] / 1024 / 1024) | round(2) if system_stats and 'disk' in system_stats and 'io' in system_stats['disk'] else 0 }}MB</p>
                        <p>写入: {{ (system_stats['disk']['io']['write_bytes'] / 1024 / 1024) | round(2) if system_stats and 'disk' in system_stats and 'io' in system_stats['disk'] else 0 }}MB</p>
                        <p>读取次数: {{ system_stats['disk']['io']['read_count'] if system_stats and 'disk' in system_stats and 'io' in system_stats['disk'] else 0 }}</p>
                        <p>写入次数: {{ system_stats['disk']['io']['write_count'] if system_stats and 'disk' in system_stats and 'io' in system_stats['disk'] else 0 }}</p>
                    </div>
                </div>
                <!-- 监控图表 -->
                <div class="charts-grid">
                    <div class="chart-container">
                        <canvas id="cpuMemoryChart"></canvas>
                    </div>
                    <div class="chart-container">
                        <canvas id="networkChart"></canvas>
                    </div>
                    <div class="chart-container">
                        <canvas id="connectionsChart"></canvas>
                    </div>
                    <div class="chart-container">
                        <canvas id="diskChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- 防火墙管理 -->
            <div id="firewall" class="content-section">
                <!-- IP封禁管理 -->
                <div class="panel">
                    <h3>IP封禁管理</h3>
                    <input type="text" id="ip-to-ban" placeholder="输入要封禁的IP">
                    <button onclick="banIP()" class="danger">封禁IP</button>
                    
                    <table>
                        <thead>
                            <tr>
                                <th>已封禁IP</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for ip in banned_ips %}
                            <tr>
                                <td>{{ ip }}</td>
                                <td><button onclick="unbanIP('{{ ip }}')" class="success">解除封禁</button></td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                <!-- 白名单管理 -->
                <div class="panel">
                    <h3>IP白名单管理</h3>
                    <input type="text" id="ip-to-whitelist" placeholder="输入要添加到白名单的IP">
                    <button onclick="addToWhitelist()" class="success">添加到白名单</button>
                    
                    <table>
                        <thead>
                            <tr>
                                <th>白名单IP</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="whitelist-table">
                            {% for ip in whitelist_ips %}
                            <tr>
                                <td>{{ ip }}</td>
                                <td><button onclick="removeFromWhitelist('{{ ip }}')" class="danger">从白名单移除</button></td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 进程管理 -->
            <div id="process" class="content-section">
                <div class="panel">
                    <h3>进程监控</h3>
                    <div class="process-controls">
                        <div class="process-filters">
                            <input type="text" id="process-search" placeholder="搜索进程...">
                            <select id="process-sort">
                                <option value="cpu">按CPU使用率排序</option>
                                <option value="memory">按内存使用率排序</option>
                                <option value="pid">按PID排序</option>
                                <option value="name">按名称排序</option>
                            </select>
                            <select id="process-filter">
                                <option value="all">所有进程</option>
                                <option value="user">用户进程</option>
                                <option value="system">系统进程</option>
                            </select>
                            <button onclick="refreshProcesses()" class="success">刷新</button>
                        </div>
                        <div class="process-summary">
                            <span>总进程数: <strong id="total-processes">{{ system_stats['processes']['total'] if system_stats and 'processes' in system_stats else 0 }}</strong></span>
                            <span>运行中: <strong id="running-processes">0</strong></span>
                            <span>休眠: <strong id="sleeping-processes">0</strong></span>
                            <span>僵尸: <strong id="zombie-processes">0</strong></span>
                        </div>
                    </div>

                    <div class="process-tree-view">
                        <div class="process-list"></div>
                    </div>

                    <!-- 进程详情对话框 -->
                    <div id="process-details" class="modal">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4>进程详情</h4>
                                <span class="close">&times;</span>
                            </div>
                            <div class="modal-body">
                                <div class="process-tabs">
                                    <button class="tab-button active" onclick="showTab('info')">基本信息</button>
                                    <button class="tab-button" onclick="showTab('resources')">资源使用</button>
                                    <button class="tab-button" onclick="showTab('files')">文件句柄</button>
                                    <button class="tab-button" onclick="showTab('network')">网络连接</button>
                                    <button class="tab-button" onclick="showTab('children')">子进程</button>
                                </div>
                                <div id="process-info" class="tab-content active"></div>
                                <div id="process-resources" class="tab-content">
                                    <canvas id="process-resource-chart"></canvas>
                                </div>
                                <div id="process-files" class="tab-content"></div>
                                <div id="process-network" class="tab-content"></div>
                                <div id="process-children" class="tab-content"></div>
                            </div>
                            <div class="modal-footer">
                                <button onclick="killProcess()" class="danger">终止进程</button>
                                <button onclick="changePriority()" class="warning">调整优先级</button>
                                <button onclick="pauseProcess()" class="info">暂停/恢复</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 网络监控 -->
            <div id="network" class="content-section">
                <!-- 网络接口信息 -->
                <div class="panel">
                    <h3>网络接口</h3>
                    {% if system_stats and 'network' in system_stats and 'interfaces' in system_stats['network'] %}
                        {% for iface, info in system_stats['network']['interfaces'].items() %}
                        <div class="network-interface">
                            <h4>{{ iface }}</h4>
                            <div class="interface-info">
                                {% if 'addresses' in info %}
                                    {% for addr in info['addresses'] %}
                                    <p>地址: {{ addr['addr'] if 'addr' in addr else '' }} ({{ addr['family'] if 'family' in addr else '' }})</p>
                                    {% endfor %}
                                {% endif %}
                                <p>状态: {{ '在线' if info['stats']['isup'] if 'stats' in info and 'isup' in info['stats'] else '离线' }}</p>
                                <p>速度: {{ info['stats']['speed'] if 'stats' in info and 'speed' in info['stats'] else 0 }}Mb/s</p>
                            </div>
                        </div>
                        {% endfor %}
                    {% endif %}
                </div>
                <!-- IP连接统计 -->
                <div class="panel">
                    <h3>IP连接统计</h3>
                    <table>
                        <thead>
                            <tr>
                                <th>IP地址</th>
                                <th>总连接数</th>
                                <th>状态详情</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% if system_stats and 'network' in system_stats and 'ip_connections' in system_stats['network'] %}
                                {% for ip, stats in system_stats['network']['ip_connections'].items() %}
                                <tr>
                                    <td>{{ ip }}</td>
                                    <td>{{ stats['total'] if 'total' in stats else 0 }}</td>
                                    <td>
                                        {% if 'states' in stats %}
                                            {% for state, count in stats['states'].items() %}
                                            {{ state }}: {{ count }}
                                            {% endfor %}
                                        {% endif %}
                                    </td>
                                </tr>
                                {% endfor %}
                            {% endif %}
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 日志查看 -->
            <div id="logs" class="content-section">
                <!-- 系统日志 -->
                <div class="panel">
                    <h3>系统日志</h3>
                    <div class="log-container">
                        <select id="log-level-filter">
                            <option value="all">所有级别</option>
                            <option value="INFO">信息</option>
                            <option value="WARNING">警告</option>
                            <option value="ERROR">错误</option>
                        </select>
                        <div id="log-entries" class="log-entries"></div>
                    </div>
                </div>
            </div>

            <!-- 系统设置 -->
            <div id="settings" class="content-section">
                <!-- 告警设置 -->
                <div class="panel">
                    <h3>告警设置</h3>
                    <div class="settings-form">
                        <div class="form-group">
                            <label>CPU使用率告警阈值 (%)</label>
                            <input type="number" id="cpu-threshold" value="{{ alert_settings['cpu_threshold'] if alert_settings else 0 }}">
                        </div>
                        <div class="form-group">
                            <label>内存使用率告警阈值 (%)</label>
                            <input type="number" id="memory-threshold" value="{{ alert_settings['memory_threshold'] if alert_settings else 0 }}">
                        </div>
                        <div class="form-group">
                            <label>连接数告警阈值</label>
                            <input type="number" id="connection-threshold" value="{{ alert_settings['connection_threshold'] if alert_settings else 0 }}">
                        </div>
                        <div class="form-group">
                            <label>
                                <input type="checkbox" id="email-notification" 
                                       {% if alert_settings and alert_settings['email_notification'] %}checked{% endif %}>
                                启用邮件通知
                            </label>
                        </div>
                        <div class="form-group">
                            <label>通知邮箱</label>
                            <input type="email" id="email-address" value="{{ alert_settings['email_address'] if alert_settings else '' }}">
                        </div>
                        <div class="form-group">
                            <label>SMTP服务器</label>
                            <input type="text" id="smtp-server" value="{{ alert_settings['smtp_server'] if alert_settings else '' }}">
                        </div>
                        <div class="form-group">
                            <label>SMTP端口</label>
                            <input type="number" id="smtp-port" value="{{ alert_settings['smtp_port'] if alert_settings else 0 }}">
                        </div>
                        <div class="form-group">
                            <label>SMTP用户名</label>
                            <input type="text" id="smtp-username" value="{{ alert_settings['smtp_username'] if alert_settings else '' }}">
                        </div>
                        <div class="form-group">
                            <label>SMTP密码</label>
                            <input type="password" id="smtp-password" value="{{ alert_settings['smtp_password'] if alert_settings else '' }}">
                        </div>
                        <button onclick="updateAlertSettings()" class="success">保存设置</button>
                    </div>
                </div>
                <!-- 其他设置 -->
                <div class="panel">
                    <h3>系统设置</h3>
                    <div class="form-group">
                        <label>仪表盘刷新频率</label>
                        <select id="refresh-rate" onchange="updateRefreshRate(this.value)">
                            <option value="500">0.5秒</option>
                            <option value="1000">1秒</option>
                            <option value="5000" selected>5秒</option>
                        </select>
                    </div>
                    <p>当前连接限制: <span id="connection-limit">{{ connection_limit }}</span></p>
                    <input type="number" id="new-limit" placeholder="新的连接限制">
                    <button onclick="updateLimit()" class="success">更新限制</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 修改显示区域切换函数
        function showSection(sectionId) {
            // 隐藏所有内容区域
            document.querySelectorAll('.content-section').forEach(section => {
                section.classList.remove('active');
            });
            
            // 显示选中的内容区域
            const section = document.getElementById(sectionId);
            section.classList.add('active');
            
            // 更新菜单项状态
            document.querySelectorAll('.menu-item').forEach(item => {
                item.classList.remove('active');
            });
            document.querySelector(`.menu-item[onclick="showSection('${sectionId}')"]`).classList.add('active');
            
            // 如果切换到进程管理页面，立即加载进程列表并显示加载状态
            if (sectionId === 'process') {
                const processList = document.querySelector('.process-list');
                processList.innerHTML = '<div class="process-item">正在加载进程数据...</div>';
                
                // 立即加载进程列表
                loadProcesses(1, 20).then(() => {
                    // 启动定期更新
                    startProcessListUpdate();
                });
            } else {
                // 如果切换到其他页面，停止进程列表更新
                stopProcessListUpdate();
            }
        }

        // 添加进程列表更新控制
        let processListUpdateTimer = null;

        function startProcessListUpdate() {
            if (!processListUpdateTimer) {
                processListUpdateTimer = setInterval(() => {
                    loadProcesses(1, 20);
                }, 30000); // 30秒更新一次
            }
        }

        function stopProcessListUpdate() {
            if (processListUpdateTimer) {
                clearInterval(processListUpdateTimer);
                processListUpdateTimer = null;
            }
        }

        // 修改进程列表加载函数
        async function loadProcesses(page = 1, pageSize = 20) {
            try {
                const response = await fetch(`/api/processes?page=${page}&size=${pageSize}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                
                if (data.error) {
                    throw new Error(data.error);
                }
                
                // 更新进程统计
                document.getElementById('total-processes').textContent = data.total;
                document.getElementById('running-processes').textContent = data.running;
                document.getElementById('sleeping-processes').textContent = data.sleeping;
                document.getElementById('zombie-processes').textContent = data.zombie;
                
                // 渲染进程列表
                const processList = document.querySelector('.process-list');
                if (data.processes.length === 0) {
                    processList.innerHTML = '<div class="process-item">没有找到进程</div>';
                    return;
                }
                
                processList.innerHTML = data.processes.map(proc => `
                    <div class="process-item" onclick="showProcessDetails(${proc.pid})">
                        <div class="status ${proc.status?.toLowerCase() || 'unknown'}"></div>
                        <div class="info">
                            <strong>${proc.name || 'Unknown'}</strong> (PID: ${proc.pid})
                            <br>
                            <small>${proc.username || 'Unknown'} | ${proc.status || 'Unknown'}</small>
                        </div>
                        <div class="stats">
                            <span>CPU: ${(proc.cpu_percent || 0).toFixed(1)}%</span>
                            <span>内存: ${(proc.memory_percent || 0).toFixed(1)}%</span>
                        </div>
                    </div>
                `).join('');
                
                // 添加分页控件
                const totalPages = data.pages;
                const pagination = document.createElement('div');
                pagination.className = 'pagination';
                pagination.innerHTML = `
                    <button onclick="loadProcesses(${page - 1}, ${pageSize})" 
                            ${page <= 1 ? 'disabled' : ''}>上一页</button>
                    <span>第 ${page} 页，共 ${totalPages} 页</span>
                    <button onclick="loadProcesses(${page + 1}, ${pageSize})"
                            ${page >= totalPages ? 'disabled' : ''}>下一页</button>
                `;
                
                // 移除旧的分页控件（如果存在）
                const oldPagination = document.querySelector('.pagination');
                if (oldPagination) {
                    oldPagination.remove();
                }
                
                // 添加新的分页控件
                processList.after(pagination);
                
            } catch (error) {
                console.error('加载进程列表失败:', error);
                showAlert('加载进程列表失败: ' + error.message, 'error');
                
                const processList = document.querySelector('.process-list');
                processList.innerHTML = `
                    <div class="process-item error">
                        <div class="info">
                            <strong>错误</strong>
                            <br>
                            <small>${error.message}</small>
                        </div>
                    </div>
                `;
            }
        }

        async function banIP() {
            const ip = document.getElementById('ip-to-ban').value;
            const response = await fetch('/api/ban_ip', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ip})
            });
            location.reload();
        }

        async function unbanIP(ip) {
            const response = await fetch('/api/unban_ip', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ip})
            });
            location.reload();
        }

        async function updateLimit() {
            const limit = document.getElementById('new-limit').value;
            const response = await fetch('/api/update_limit', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({limit: parseInt(limit)})
            });
            location.reload();
        }

        // 添加 WebSocket 连接
        let ws = null;
        let reconnectAttempts = 0;
        const maxReconnectAttempts = 5;
        let refreshRate = 5000; // 默认5秒
        let wsUpdateTimer = null;

        // 更新刷新频率
        function updateRefreshRate(rate) {
            refreshRate = parseInt(rate);
            // 保存到localStorage
            localStorage.setItem('dashboard-refresh-rate', rate);
            
            // 重新连接WebSocket以应用新的刷新频率
            if (ws) {
                ws.close();
                connectWebSocket();
            }
        }

        function connectWebSocket() {
            if (ws) {
                ws.close();
            }
            
            // 清除现有的更新定时器
            if (wsUpdateTimer) {
                clearInterval(wsUpdateTimer);
            }
            
            try {
                // 使用正确的WebSocket URL
                const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                const wsUrl = `${protocol}//${window.location.host}/ws/stats`;
                
                ws = new WebSocket(wsUrl);
                
                ws.onopen = function() {
                    console.log('WebSocket连接已建立');
                    reconnectAttempts = 0;
                    
                    // 立即请求一次数据
                    if (ws.readyState === WebSocket.OPEN) {
                        ws.send('get_stats');
                    }
                    
                    // 设置新的更新定时器
                    wsUpdateTimer = setInterval(() => {
                        if (ws && ws.readyState === WebSocket.OPEN) {
                            ws.send('get_stats');
                        } else {
                            // 如果连接已关闭，尝试重新连接
                            clearInterval(wsUpdateTimer);
                            reconnect();
                        }
                    }, refreshRate);
                };
                
                ws.onmessage = function(event) {
                    try {
                        // 解压数据
                        const blob = event.data;
                        const reader = new FileReader();
                        reader.onload = function() {
                            try {
                                let decompressed;
                                try {
                                    const compressed = new Uint8Array(reader.result);
                                    decompressed = pako.inflate(compressed, { to: 'string' });
                                } catch (error) {
                                    // 如果解压失败，尝试直接解析数据
                                    decompressed = new TextDecoder().decode(blob);
                                }
                                const data = JSON.parse(decompressed);
                                
                                // 检查认证错误
                                if (data.error === 'unauthorized') {
                                    console.error('会话已过期，正在重新加载页面...');
                                    showAlert('会话已过期，请重新登录', 'error');
                                    setTimeout(() => {
                                        window.location.reload();
                                    }, 2000);
                                    return;
                                }
                                
                                // 更新UI
                                updateStatsUI(data);
                            } catch (error) {
                                console.error('处理数据失败:', error);
                                // 检查是否是HTML响应（会话过期）
                                if (decompressed && decompressed.includes('<!DOCTYPE')) {
                                    console.error('会话已过期，正在重新加载页面...');
                                    showAlert('会话已过期，请重新登录', 'error');
                                    setTimeout(() => {
                                        window.location.reload();
                                    }, 2000);
                                    return;
                                }
                            }
                        };
                        reader.readAsArrayBuffer(blob);
                    } catch (error) {
                        console.error('处理WebSocket消息失败:', error);
                    }
                };
                
                ws.onclose = function(event) {
                    console.log('WebSocket连接已关闭', event.code, event.reason);
                    // 清除更新定时器
                    if (wsUpdateTimer) {
                        clearInterval(wsUpdateTimer);
                    }
                    // 尝试重新连接
                    reconnect();
                };
                
                ws.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                };
                
            } catch (error) {
                console.error('建立WebSocket连接失败:', error);
                // 尝试重新连接
                reconnect();
            }
        }

        // 修改重连函数
        function reconnect() {
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++;
                console.log(`尝试重新连接 (${reconnectAttempts}/${maxReconnectAttempts})...`);
                // 先检查会话状态
                fetch('/api/check-session')
                    .then(response => response.json())
                    .then(data => {
                        if (data.authenticated) {
                            setTimeout(connectWebSocket, 5000);
                        } else {
                            console.error('会话已过期，正在重新加载页面...');
                            showAlert('会话已过期，请重新登录', 'error');
                            setTimeout(() => {
                                window.location.reload();
                            }, 2000);
                        }
                    })
                    .catch(error => {
                        console.error('检查会话状态失败:', error);
                        setTimeout(connectWebSocket, 5000);
                    });
            } else {
                console.log('达到最大重连次数，停止重连');
                showAlert('连接失败，请刷新页面重试', 'error');
            }
        }

        // 更新UI的函数
        function updateStatsUI(stats) {
            try {
                // 只更新发生变化的部分
                if (stats.cpu) {
                    updateCPUStats(stats.cpu);
                }
                if (stats.memory) {
                    updateMemoryStats(stats.memory);
                }
                if (stats.disk) {
                    updateDiskStats(stats.disk);
                }
                if (stats.network) {
                    updateNetworkStats(stats.network);
                }
                if (stats.timestamp) {
                    document.getElementById('timestamp').textContent = stats.timestamp;
                }
            } catch (error) {
                console.error('更新UI失败:', error);
            }
        }

        // 在页面加载时恢复保存的刷新频率
        document.addEventListener('DOMContentLoaded', function() {
            // 从localStorage获取保存的刷新频率
            const savedRate = localStorage.getItem('dashboard-refresh-rate');
            if (savedRate) {
                refreshRate = parseInt(savedRate);
                document.getElementById('refresh-rate').value = savedRate;
            }
            
            // 延迟一秒后连接WebSocket，确保页面完全加载
            setTimeout(connectWebSocket, 1000);
        });

        // 在页面卸载时清理
        window.addEventListener('unload', function() {
            if (ws) {
                ws.close();
            }
            if (wsUpdateTimer) {
                clearInterval(wsUpdateTimer);
            }
        });

        async function addToWhitelist() {
            const ip = document.getElementById('ip-to-whitelist').value;
            const response = await fetch('/api/whitelist/add', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ip})
            });
            location.reload();
        }

        async function removeFromWhitelist(ip) {
            const response = await fetch('/api/whitelist/remove', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ip})
            });
            location.reload();
        }

        async function updateAlertSettings() {
            const settings = {
                cpu_threshold: parseInt(document.getElementById('cpu-threshold').value),
                memory_threshold: parseInt(document.getElementById('memory-threshold').value),
                connection_threshold: parseInt(document.getElementById('connection-threshold').value),
                email_notification: document.getElementById('email-notification').checked,
                email_address: document.getElementById('email-address').value,
                smtp_server: document.getElementById('smtp-server').value,
                smtp_port: parseInt(document.getElementById('smtp-port').value),
                smtp_username: document.getElementById('smtp-username').value,
                smtp_password: document.getElementById('smtp-password').value
            };

            try {
                const response = await fetch('/api/alert-settings', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(settings)
                });
                const result = await response.json();
                
                if (result.status === 'success') {
                    showAlert('告警设置已更新', 'success');
                } else {
                    showAlert(result.message || '更新失败', 'error');
                }
            } catch (error) {
                showAlert('更新设置失败: ' + error, 'error');
            }
        }

        async function updateLogs() {
            const response = await fetch('/api/logs');
            const logs = await response.json();
            const logLevel = document.getElementById('log-level-filter').value;
            const logContainer = document.getElementById('log-entries');
            
            logContainer.innerHTML = logs
                .filter(log => logLevel === 'all' || log.level === logLevel)
                .map(log => `
                    <div class="log-entry ${log.level.toLowerCase()}">
                        <span class="log-time">${log.timestamp}</span>
                        <span class="log-level">${log.level}</span>
                        <span class="log-message">${log.message}</span>
                    </div>
                `).join('');
        }

        // 每30秒更新一次日志
        setInterval(updateLogs, 30000);
        updateLogs();

        // 初始化图表
        const cpuMemoryChart = new Chart(document.getElementById('cpuMemoryChart'), {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: 'CPU使用率',
                    borderColor: '#2196F3',
                    data: [],
                    fill: false
                }, {
                    label: '内存使用率',
                    borderColor: '#4CAF50',
                    data: [],
                    fill: false
                }, {
                    label: 'CPU告警阈值',
                    borderColor: '#f44336',
                    borderDash: [5, 5],
                    data: [],
                    fill: false
                }, {
                    label: '内存告警阈值',
                    borderColor: '#ff9800',
                    borderDash: [5, 5],
                    data: [],
                    fill: false
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'CPU和内存使用率监控'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        grid: {
                            color: (context) => {
                                if (context.tick.value === {{ alert_settings['cpu_threshold'] if alert_settings else 0 }}) {
                                    return '#f44336';
                                } else if (context.tick.value === {{ alert_settings['memory_threshold'] if alert_settings else 0 }}) {
                                    return '#ff9800';
                                }
                                return '#ddd';
                            }
                        }
                    }
                }
            }
        });

        const networkChart = new Chart(document.getElementById('networkChart'), {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '网络入流量 (KB/s)',
                    borderColor: '#FFA726',
                    data: []
                }, {
                    label: '网络出流量 (KB/s)',
                    borderColor: '#FF7043',
                    data: []
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });

        const connectionsChart = new Chart(document.getElementById('connectionsChart'), {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '活动连接数',
                    borderColor: '#9C27B0',
                    data: [],
                    fill: false
                }, {
                    label: '连接数告警阈值',
                    borderColor: '#f44336',
                    borderDash: [5, 5],
                    data: [],
                    fill: false
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: '连接数监控'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: (context) => {
                                if (context.tick.value === {{ alert_settings['connection_threshold'] if alert_settings else 0 }}) {
                                    return '#f44336';
                                }
                                return '#ddd';
                            }
                        }
                    }
                }
            }
        });

        const diskChart = new Chart(document.getElementById('diskChart'), {
            type: 'doughnut',
            data: {
                labels: ['已使用', '可用'],
                datasets: [{
                    data: [
                        {{ system_stats['disk']['used'] if system_stats and 'disk' in system_stats else 0 }},
                        {{ system_stats['disk']['total'] if system_stats and 'disk' in system_stats else 0 - system_stats['disk']['used'] if system_stats and 'disk' in system_stats else 0 }}
                    ],
                    backgroundColor: ['#f44336', '#4CAF50']
                }]
            },
            options: {
                responsive: true
            }
        });

        // 修改图表更新逻辑，减少更新频率
        let chartUpdateInterval = 30000; // 30秒更新一次
        let lastChartUpdate = 0;

        async function updateCharts() {
            const now = Date.now();
            if (now - lastChartUpdate < chartUpdateInterval) return;
            
            try {
                const response = await fetch('/api/history');
                const history = await response.json();
                
                // 更新CPU和内存图表
                cpuMemoryChart.data.labels = history.timestamps;
                cpuMemoryChart.data.datasets[0].data = history.cpu;
                cpuMemoryChart.data.datasets[1].data = history.memory;
                
                // 添加告警阈值线
                const cpuThreshold = {{ alert_settings['cpu_threshold'] if alert_settings else 0 }};
                const memoryThreshold = {{ alert_settings['memory_threshold'] if alert_settings else 0 }};
                cpuMemoryChart.data.datasets[2].data = new Array(history.timestamps.length).fill(cpuThreshold);
                cpuMemoryChart.data.datasets[3].data = new Array(history.timestamps.length).fill(memoryThreshold);
                
                // 检查是否超过阈值
                const cpuOverThreshold = history.cpu.some(value => value > cpuThreshold);
                const memoryOverThreshold = history.memory.some(value => value > memoryThreshold);
                
                if (cpuOverThreshold || memoryOverThreshold) {
                    showAlert('系统资源使用率超过告警阈值！');
                }
                
                cpuMemoryChart.update();
                
                // 更新网络图表
                networkChart.data.labels = history.timestamps;
                networkChart.data.datasets[0].data = history.network_in;
                networkChart.data.datasets[1].data = history.network_out;
                networkChart.update();
                
                // 更新连接数图表
                connectionsChart.data.labels = history.timestamps;
                connectionsChart.data.datasets[0].data = history.connections;
                connectionsChart.data.datasets[1].data = new Array(history.timestamps.length).fill({{ alert_settings['connection_threshold'] if alert_settings else 0 }});
                
                // 检查连接数是否超过阈值
                const connectionsOverThreshold = history.connections.some(value => value > {{ alert_settings['connection_threshold'] if alert_settings else 0 }});
                if (connectionsOverThreshold) {
                    showAlert('连接数超过告警阈值！');
                }
                
                connectionsChart.update();
                
                lastChartUpdate = now;
            } catch (error) {
                console.error('更新图表失败:', error);
            }
        }

        // 每10秒更新一次图表
        setInterval(updateCharts, 10000);
        updateCharts();

        // 添加告警提示功能
        function showAlert(message, type) {
            if (!document.getElementById('alert-container')) {
                const alertContainer = document.createElement('div');
                alertContainer.id = 'alert-container';
                alertContainer.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    z-index: 1000;
                `;
                document.body.appendChild(alertContainer);
            }

            const alert = document.createElement('div');
            alert.className = `alert ${type === 'success' ? 'success' : 'danger'}`;
            alert.style.cssText = `
                padding: 15px;
                margin-bottom: 10px;
                border-radius: 4px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                animation: slideIn 0.5s ease-out;
            `;
            alert.textContent = message;

            const alertContainer = document.getElementById('alert-container');
            alertContainer.appendChild(alert);

            setTimeout(() => {
                alert.style.animation = 'slideOut 0.5s ease-out';
                setTimeout(() => alertContainer.removeChild(alert), 450);
            }, 5000);
        }

        // 添加动画样式
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);

        let currentPid = null;
        let processResourceChart = null;
        let processHistory = {};

        async function showProcessDetails(pid) {
            try {
                const response = await fetch(`/api/process/${pid}`);
                const process = await response.json();
                
                currentPid = pid;
                
                // 更新基本信息标签页
                document.getElementById('process-info').innerHTML = `
                    <table>
                        <tr><td>进程名:</td><td>${process.name}</td></tr>
                        <tr><td>PID:</td><td>${process.pid}</td></tr>
                        <tr><td>用户:</td><td>${process.username}</td></tr>
                        <tr><td>状态:</td><td>${process.status}</td></tr>
                        <tr><td>CPU使用率:</td><td>${process.cpu_percent.toFixed(1)}%</td></tr>
                        <tr><td>内存使用率:</td><td>${process.memory_percent.toFixed(1)}%</td></tr>
                        <tr><td>内存使用:</td><td>${formatBytes(process.memory_info.rss)}</td></tr>
                        <tr><td>虚拟内存:</td><td>${formatBytes(process.memory_info.vms)}</td></tr>
                        <tr><td>创建时间:</td><td>${process.create_time}</td></tr>
                        <tr><td>命令行:</td><td>${process.cmdline}</td></tr>
                        <tr><td>线程数:</td><td>${process.num_threads}</td></tr>
                        <tr><td>优先级:</td><td>${process.nice}</td></tr>
                    </table>
                `;
                
                // 初始化资源使用图表
                initResourceChart();
                
                // 更新文件句柄标签页
                updateFileHandles(process);
                
                // 更新网络连接标签页
                updateNetworkConnections(process);
                
                // 更新子进程标签页
                updateChildProcesses(process);
                
                // 显示对话框并激活第一个标签
                document.getElementById('process-details').style.display = 'flex';
                showTab('info');
            } catch (error) {
                console.error('加载进程详情失败:', error);
                showAlert('加载进程详情失败: ' + error, 'error');
            }
        }

        function showTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 取消所有标签按钮的激活状态
            document.querySelectorAll('.tab-button').forEach(button => {
                button.classList.remove('active');
            });
            
            // 显示选中的标签页内容
            document.getElementById(`process-${tabName}`).classList.add('active');
            
            // 激活对应的标签按钮
            document.querySelector(`.tab-button[onclick="showTab('${tabName}')"]`).classList.add('active');
            
            // 如果是资源标签页，更新图表
            if (tabName === 'resources' && processResourceChart) {
                processResourceChart.update();
            }
        }

        function initResourceChart() {
            const ctx = document.getElementById('process-resource-chart').getContext('2d');
            
            if (!processResourceChart) {
                processResourceChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'CPU使用率',
                            borderColor: '#2196F3',
                            data: []
                        }, {
                            label: '内存使用率',
                            borderColor: '#4CAF50',
                            data: []
                        }]
                    },
                    options: {
                        responsive: true,
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 100
                            }
                        }
                    }
                });
            }
        }

        async function updateFileHandles(process) {
            try {
                const fileList = document.getElementById('process-files');
                if (process.open_files && process.open_files.length > 0) {
                    fileList.innerHTML = `
                        <table>
                            <thead>
                                <tr>
                                    <th>文件路径</th>
                                    <th>文件描述符</th>
                                    <th>位置</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${process.open_files.map(file => `
                                    <tr>
                                        <td>${file.path}</td>
                                        <td>${file.fd}</td>
                                        <td>${file.position}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    `;
                } else {
                    fileList.innerHTML = '<p>没有打开的文件</p>';
                }
            } catch (error) {
                console.error('更新文件句柄失败:', error);
            }
        }

        async function updateNetworkConnections(process) {
            try {
                const networkList = document.getElementById('process-network');
                if (process.connections && process.connections.length > 0) {
                    networkList.innerHTML = `
                        <table>
                            <thead>
                                <tr>
                                    <th>类型</th>
                                    <th>本地地址</th>
                                    <th>远程地址</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${process.connections.map(conn => `
                                    <tr>
                                        <td>${conn.type}</td>
                                        <td>${conn.laddr}</td>
                                        <td>${conn.raddr || '-'}</td>
                                        <td>${conn.status}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    `;
                } else {
                    networkList.innerHTML = '<p>没有活动的网络连接</p>';
                }
            } catch (error) {
                console.error('更新网络连接失败:', error);
            }
        }

        async function updateChildProcesses(process) {
            try {
                const childList = document.getElementById('process-children');
                if (process.children && process.children.length > 0) {
                    childList.innerHTML = `
                        <table>
                            <thead>
                                <tr>
                                    <th>PID</th>
                                    <th>名称</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${process.children.map(child => `
                                    <tr>
                                        <td>${child.pid}</td>
                                        <td>${child.name}</td>
                                        <td>${child.status}</td>
                                        <td>
                                            <button onclick="showProcessDetails(${child.pid})" class="info">查看</button>
                                            <button onclick="killProcess(${child.pid})" class="danger">终止</button>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    `;
                } else {
                    childList.innerHTML = '<p>没有子进程</p>';
                }
            } catch (error) {
                console.error('更新子进程列表失败:', error);
            }
        }

        function formatBytes(bytes) {
            const units = ['B', 'KB', 'MB', 'GB'];
            let size = bytes;
            let unitIndex = 0;
            while (size >= 1024 && unitIndex < units.length - 1) {
                size /= 1024;
                unitIndex++;
            }
            return `${size.toFixed(2)} ${units[unitIndex]}`;
        }

        // 修改进程详情更新逻辑
        let processUpdateInterval = 5000; // 5秒更新一次
        let lastProcessUpdate = 0;

        async function updateProcessDetails() {
            if (!currentPid || document.getElementById('process-details').style.display !== 'flex') return;
            
            const now = Date.now();
            if (now - lastProcessUpdate < processUpdateInterval) return;
            
            try {
                const response = await fetch(`/api/process/${currentPid}`);
                const process = await response.json();
                
                // 更新资源图表数据
                if (processResourceChart) {
                    const timestamp = new Date().toLocaleTimeString();
                    processResourceChart.data.labels.push(timestamp);
                    processResourceChart.data.datasets[0].data.push(process.cpu_percent);
                    processResourceChart.data.datasets[1].data.push(process.memory_percent);
                    
                    // 保持最近30个数据点
                    if (processResourceChart.data.labels.length > 30) {
                        processResourceChart.data.labels.shift();
                        processResourceChart.data.datasets[0].data.shift();
                        processResourceChart.data.datasets[1].data.shift();
                    }
                    
                    processResourceChart.update();
                }
                
                // 如果相应的标签页处于活动状态，则更新其内容
                if (document.getElementById('process-files').classList.contains('active')) {
                    updateFileHandles(process);
                }
                if (document.getElementById('process-network').classList.contains('active')) {
                    updateNetworkConnections(process);
                }
                if (document.getElementById('process-children').classList.contains('active')) {
                    updateChildProcesses(process);
                }
                
                lastProcessUpdate = now;
            } catch (error) {
                console.error('更新进程详情失败:', error);
            }
        }

        // 修改进程详情对话框的初始化和关闭功能
        document.addEventListener('DOMContentLoaded', function() {
            const modal = document.getElementById('process-details');
            const closeBtn = modal.querySelector('.close');
            
            // 确保对话框初始时是隐藏的
            modal.style.display = 'none';
            
            // 点击关闭按钮关闭对话框
            closeBtn.onclick = function() {
                modal.style.display = 'none';
                currentPid = null;
                if (processResourceChart) {
                    processResourceChart.destroy();
                    processResourceChart = null;
                }
            };
            
            // 点击对话框外部关闭对话框
            window.onclick = function(event) {
                if (event.target === modal) {
                    modal.style.display = 'none';
                    currentPid = null;
                    if (processResourceChart) {
                        processResourceChart.destroy();
                        processResourceChart = null;
                    }
                }
            };
            
            // ESC键关闭对话框
            document.addEventListener('keydown', function(event) {
                if (event.key === 'Escape' && modal.style.display === 'flex') {
                    modal.style.display = 'none';
                    currentPid = null;
                    if (processResourceChart) {
                        processResourceChart.destroy();
                        processResourceChart = null;
                    }
                }
            });
        });

        // 添加更新各个状态的函数
        function updateCPUStats(cpu) {
            const cpuCard = document.querySelector('.stat-card:nth-child(1)');
            if (cpuCard) {
                const cpuFill = cpuCard.querySelector('.progress-fill');
                const cpuText = cpuCard.querySelector('p');
                if (cpuFill && cpuText) {
                    const cpuPercent = cpu.percent;
                    cpuFill.style.width = `${cpuPercent}%`;
                    cpuFill.className = `progress-fill ${cpuPercent > 80 ? 'critical' : cpuPercent > 60 ? 'warning' : ''}`;
                    cpuText.innerHTML = `
                        ${cpuPercent.toFixed(1)}% (${cpu.cores}核心)<br>
                        频率: ${(cpu.frequency.current/1000).toFixed(2)}GHz<br>
                        负载: ${cpu.load_average['1min'].toFixed(2)}
                    `;
                }
            }
        }

        function updateMemoryStats(memory) {
            const memCard = document.querySelector('.stat-card:nth-child(2)');
            if (memCard) {
                const memFill = memCard.querySelector('.progress-fill');
                const memText = memCard.querySelector('p');
                if (memFill && memText) {
                    const memPercent = memory.percent;
                    const memUsed = (memory.used / 1024 / 1024 / 1024).toFixed(2);
                    const memTotal = (memory.total / 1024 / 1024 / 1024).toFixed(2);
                    memFill.style.width = `${memPercent}%`;
                    memFill.className = `progress-fill ${memPercent > 80 ? 'critical' : memPercent > 60 ? 'warning' : ''}`;
                    memText.innerHTML = `
                        ${memUsed}GB / ${memTotal}GB (${memPercent}%)<br>
                        交换: ${(memory.swap.used / 1024 / 1024 / 1024).toFixed(2)}GB / 
                        ${(memory.swap.total / 1024 / 1024 / 1024).toFixed(2)}GB
                    `;
                }
            }
        }

        function updateDiskStats(disk) {
            const diskCard = document.querySelector('.stat-card:nth-child(3)');
            if (diskCard) {
                const diskFill = diskCard.querySelector('.progress-fill');
                const diskText = diskCard.querySelector('p');
                if (diskFill && diskText) {
                    const diskPercent = disk.percent;
                    const diskUsed = (disk.used / 1024 / 1024 / 1024).toFixed(2);
                    const diskTotal = (disk.total / 1024 / 1024 / 1024).toFixed(2);
                    diskFill.style.width = `${diskPercent}%`;
                    diskFill.className = `progress-fill ${diskPercent > 80 ? 'critical' : diskPercent > 60 ? 'warning' : ''}`;
                    diskText.innerHTML = `
                        ${diskUsed}GB / ${diskTotal}GB (${diskPercent}%)<br>
                        读取: ${(disk.io.read_bytes / 1024 / 1024).toFixed(2)}MB<br>
                        写入: ${(disk.io.write_bytes / 1024 / 1024).toFixed(2)}MB
                    `;
                }
            }
        }

        function updateNetworkStats(network) {
            const netCard = document.querySelector('.stat-card:nth-child(4)');
            if (netCard) {
                const netText = netCard.querySelector('p');
                if (netText) {
                    const sent = (network.bytes_sent / 1024 / 1024).toFixed(2);
                    const recv = (network.bytes_recv / 1024 / 1024).toFixed(2);
                    const conn = network.connections.ESTABLISHED;
                    netText.innerHTML = `
                        发送: ${sent}MB<br>
                        接收: ${recv}MB<br>
                        连接数: ${conn}
                    `;
                }
            }
        }
    </script>
</body>
</html> 